﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using CommandType = Library.CommandType;
using Library;
namespace ClientFrm
{
    public partial class PlaysFrm : Form
    {
        private string _userName;
        private Socket _clientSocket;
        private byte[] _buffer;
        public PlaysFrm(Socket _client, string _name)
        {
            _clientSocket = _client;
            _userName = _name;
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;
        }
        Label X;
        int i = 20;
        bool stop = false;

        public PlaysFrm()
        {
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;
        }
        int count1 =10;
        private void toiluot(bool a)
        {
            btnbb.Enabled = a;
            btnboqua.Enabled = a;
        }
        Thread chaytg;
        void ChayThoiGian()
        {
            while (true)
            {
                Thread.Sleep(1);
                    while (i >= 0 && stop)
                    {
                        X.Text = i.ToString();
                        Thread.Sleep(1000);
                        i--;
                        if (i == 0)
                        {
                            btnboqua.PerformClick();
                        }
                    }
            }
        }

        private void PlaysFrm_Load(object sender, EventArgs e)
        {
            chaytg = new Thread(ChayThoiGian);
           
            this.Hide();
           
            var dialog = new LoginFrm();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                toiluot(false);
                LoadBai(false);
                _userName = dialog.UserName;
                _clientSocket = dialog.ClientSocket;
                groupBox7.Text = dialog.UserName;

                _buffer = new byte[1024];
                _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                                           SocketFlags.None, OnMessageReceived, null);
                var msg = new ChatMessage(_buffer);
                chaytg.Start();
            }
            else this.Close();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            
            
            count1--;
            if (count1 == 0)
            {
                timer1.Stop();
            }
            lbtime.Text = count1.ToString();
    
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (_clientSocket != null)
            {
                chaytg.Abort();
                var msg = new ChatMessage()
                {
                    SenderName = _userName,
                    MsgBody = "quit",
                    CmdType = CommandType.ClientOut
                };
                var buffer = msg.ToByteArray();
                _clientSocket.BeginSend(buffer, 0, buffer.Length,
                                SocketFlags.None, OnMessageSent, null);

                Thread.Sleep(100);

                _clientSocket.Shutdown(SocketShutdown.Both);
                _clientSocket.Close();
            }
        }
        #region Trạng Thái
        List<GroupBox> gp;
        private void LoadBai(bool a)
        {
            pictureBox12.Visible = false;
            gp = this.Controls.Cast<Control>().Where(x => x is GroupBox).Cast<GroupBox>().ToList();
            foreach (var _gp in gp )
            {
                if (_gp != groupBox7)
                {
                    _gp.Visible = a;
                }
                _gp.Controls.Cast<Control>().Where(x => x.Tag != null && x.Tag.ToString().CompareTo("btnMoBai") == 0).ToList().ForEach(x => x.Visible = a);
                _gp.Controls.Cast<Control>().Where(x => x.Tag != null && x.Tag.ToString().CompareTo("pbLaBai") == 0).ToList().ForEach(x => x.Visible = a);
            }
    
            btnbd.Visible = a;
            lbbatdauchoi.Visible = a;

        }
        private void PhatBai(bool a)
        {
            pb1_1.Visible = a;
            pb1_2.Visible = a;
            pb2_1.Visible = a;
            pb2_2.Visible = a;
            pb3_1.Visible = a;
            pb3_2.Visible = a;
            pb4_1.Visible = a;
            pb4_2.Visible = a;
            pb5_1.Visible = a;
            pb5_2.Visible = a;
            pb5_1.Visible = a;
            pb6_1.Visible = a;
            pb6_2.Visible = a;
            pb7_1.Visible = a;
            pb7_2.Visible = a;
            pb8_1.Visible = a;
            pb8_2.Visible = a;
        }
        void Batdauchoi(bool a)
        {
            foreach (var _gp in gp)
            {
                if (_gp != groupBox7)
                {
                    _gp.Controls.Cast<Control>().Where(x => x.Tag != null && x.Tag.ToString().CompareTo("btnMoBai") == 0).ToList().ForEach(x => x.Visible = a);
                } 
            }
            
        }
        #endregion
        private List<PictureBox> SapXep(GroupBox gb)
        {
            List<PictureBox> lpb = new List<PictureBox>();
            int count = gb.Controls.Cast<Control>().Where(x => x is PictureBox).ToList().Count;
            for (int d = 0; d < count; d++)
            {
                lpb.Add(gb.Controls.Cast<Control>().Where(x => x is PictureBox).ToList()[d] as PictureBox);
            }
            for (int i = 0; i<lpb.Count-1; i++)
            {
                for (int j = i + 1; j < lpb.Count; j++)
                {
                    if (int.Parse(lpb[j].Name.Split('_')[1].ToString()) < int.Parse(lpb[i].Name.Split('_')[1].ToString()))
                    {
                        PictureBox tam = lpb[j];
                        lpb[j] = lpb[i];
                        lpb[i] = tam;
                    }
                }
            }
            return lpb;
        }
        private void OnMessageReceived(IAsyncResult ar)
        {
            try
            {
                _clientSocket.EndReceive(ar);
                
                var recvMsg = new ChatMessage(_buffer);

                switch (recvMsg.CmdType)
                {
                    #region Login tính đập chai
                    case CommandType.ClientLogin:
                        _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                                         SocketFlags.None,
                                         OnMessageReceived, null);

                        if (recvMsg.MsgBody.ToString() == "TruongPhong")
                        {
                            foreach (var _gp in gp)
                            {
                                if (_gp.Visible == false)
                                {
                                    _gp.Visible = true;
                                    _gp.Text = recvMsg.SenderName;
                                    _gp.Controls.Cast<Control>().Where(x => x is Label).ToList()[0].Text = "Chủ Phòng";
                                    break;
                                }
                            }
                        }
                        else
                        {
                            foreach (var _gp in gp)
                            {
                                if (_gp.Visible == false)
                                {
                                    _gp.Visible = true;
                                    _gp.Text = recvMsg.SenderName;
                                    break;
                                }
                            }
                        }
                        break;
                    #endregion
                    case CommandType.ChuRoom:
                            groupBox7.Controls.Cast<Control>().Where(x => x is Label).ToList()[0].Text = "Chủ Phòng";
                            btnSS.Visible = false;
                        break;
                    case CommandType.Message:
                        listView1.Items.Add(
                            new ListViewItem(
                                new string[] { recvMsg.SenderName, recvMsg.MsgBody.ToString() }
                                ));
                        break;
                    case CommandType.ClientOut:
                        var player = gp.Find(x => x.Text == recvMsg.SenderName);
                        player.Visible = false;
                        break;
                    #region Tính Đập Chai
                    case CommandType.BocBai:
                        #region boc bai
                        if (recvMsg.MsgBody.ToString() != "No")
                        {
                            if (recvMsg.SenderName == _userName)
                            {
                                int vt = int.Parse(recvMsg.MsgBody.ToString());

                                foreach (PictureBox pb in SapXep(groupBox7))
                                {
                                    if (pb.Visible == false)
                                    {
                                        pb.Image = imageListQuanBai.Images[vt];
                                        pb.Visible = true;
                                        break;
                                    }
                                }

                            }
                            else
                            {
                                foreach (var gp1 in this.Controls.Cast<Control>().Where(x => x is GroupBox).ToList())
                                {
                                    if (gp1.Text == recvMsg.SenderName)
                                    {
                                        foreach (var pb in SapXep(gp1 as GroupBox))
                                        {
                                            if (pb.Visible == false)
                                            {
                                                pb.Visible = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                            MessageBox.Show("Số Điểm Của Bạn Đã vượt Mức Cho Phép");
                        #endregion
                        break;
                        
                    case CommandType.PhatBai:
                        
                        xuli(recvMsg);
                        _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                                     SocketFlags.None, OnMessageReceived, null);
                        return;
                    case CommandType.SanSang:   
                        foreach (var gp1 in this.Controls.Cast<Control>().Where(x => x is GroupBox).ToList())
                        {
                            if (gp1.Text == recvMsg.SenderName)
                            {
                                gp1.Controls.Cast<Control>().Where(x => x is Label).ToList()[0].Text = "Sẵn Sàng";
                            }
                        }
                        break;
                    case CommandType.ToiLuot:

                            if (X != null) X.Text = "Qua Lượt";
                           
                                X = this.Controls.Cast<Control>().Where(gr => gr.Text == recvMsg.SenderName).
                                              ToList()[0].Controls.Cast<Control>().Where(x => x is Label).ToList()[0] as Label;
                                i = 20;
                                stop = true;
                                if (recvMsg.SenderName == _userName)
                                {
                                    toiluot(true);
                                }
                        break;
                    case CommandType.Boqua:
                        var gr1 = this.Controls.Cast<Control>().Where(x => x is GroupBox && x.Text == recvMsg.SenderName).ToList()[0];
                        //stop = true;
                        gr1.Controls.Cast<Control>().Where(x => x is Label).ToList()[0].Text = "Qua Lượt";
                        
                        break;
                    case CommandType.BatDauChoi:
                        stop = false;
                        //pictureBox12.Visible = true;
                            this.Controls.Cast<Control>().Where(gr => gr.Text == recvMsg.SenderName).
                                                  ToList()[0].Controls.Cast<Control>().Where(x => x is Label).ToList()[0].Text = "Cái Đi Xét";
                            lbbatdauchoi.Visible = true;

                            if (_userName == recvMsg.SenderName)
                                Batdauchoi(true);
                        break;
                    case CommandType.MoBai:
                        var gp2 = gp.Find(x => x.Text == recvMsg.SenderName);
                        var s= recvMsg.MsgBody.ToString().Trim().Split('/');
                        var bai = gp2.Controls.Cast<Control>().Where(x => x.Tag != null && x.Tag.ToString().CompareTo("pbLaBai")==0).ToList();
                        i = 4;
                        var s1 = s[0].Trim().Split(' ');
                        for(int j=0;j<s1.Length;j++)
                        {
                            (bai[i] as PictureBox).Image = imageListQuanBai.Images[int.Parse(s1[j])];
                            i--;
                        }
                        lbbatdauchoi.Text = s[1].ToString();
                        string s3 = s[1].Trim().Split(' ')[0], s4 = s[1].Trim().Split(' ')[2], kq = s[1].Trim().Split(' ')[1];
                        kiemtrathangthua(gp.Find(x => x.Text == s3).Controls.Cast<Control>().Where(x => x is Label).ToList()[0] as Label,gp.Find(x => x.Text == s4).Controls.Cast<Control>().Where(x => x is Label).ToList()[0] as Label, kq);
                        break;
                    #endregion
                }

                if (recvMsg.CmdType != CommandType.ClientLogin && recvMsg.CmdType != CommandType.PhatBai)
                {
                    _buffer = new byte[1024];
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                   SocketFlags.None,
                   OnMessageReceived, null);
                }
                    
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void kiemtrathangthua(Label lb1, Label lb2, string s)
        {
                if (s == "Thắng")
                    lb2.Text = "Thua";
                else if (s == "Thua")
                    lb2.Text = "Thắng";
                else
                    lb2.Text = "Huề";
        }
       
        private void xuli(ChatMessage recvMsg)
        {
            if (recvMsg.MsgBody.ToString()== "")
            {
                btnbd.Visible = true;
            }
            else
            {
                int[] a = new int[2];
                for (int i = 0; i < 2; i++)
                {
                    a[i] = int.Parse(recvMsg.MsgBody.ToString().Split(' ')[i]);
                }
                pb1_1.Image = imageListQuanBai.Images[a[0]];
                pb1_2.Image = imageListQuanBai.Images[a[1]];
                this.PhatBai(true);
                pictureBox12.Visible = true;
                btnSS.Enabled = false;
            }
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMessage.Text))
            {
                MessageBox.Show("chua nhap thong diep ", "loi ");
                return;
            }
            listView1.Items.Add(
                new ListViewItem(new[] { _userName, txtMessage.Text, }));
            var msg = new ChatMessage()
            {
                SenderName = _userName,
                MsgBody = txtMessage.Text,
                CmdType = CommandType.Message
            };
            buffer = msg.ToByteArray();
            _clientSocket.BeginSend(buffer, 0, buffer.Length,
                        SocketFlags.None, OnMessageSent, null);

            txtMessage.Text = "";
        }

        private void OnMessageSent(IAsyncResult ar)
        {
            try
            {
                _clientSocket.EndSend(ar);
                DialogResult = DialogResult.OK;
            }
            catch
            {
                DialogResult = DialogResult.Cancel;
            }
        }

        private void txtMessage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnsend.PerformClick();
        }

        private void btnbd_Click(object sender, EventArgs e)
        {
            btnbd.Visible = false;
            pictureBox12.Visible = true;
            var msg = new ChatMessage()
            {
                SenderName = _userName,
                MsgBody = "",
                CmdType = CommandType.PhatBai
            };
            buffer = msg.ToByteArray();
            _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, OnMessageSent, null);
            
           // pictureBox1.Image = imageListQuanBai.Images[1];
        }
       byte[] buffer;
        private void btnbb_Click(object sender, EventArgs e)
        {

            var msg = new ChatMessage()
            {
                SenderName = _userName,
                MsgBody = "",
                CmdType = CommandType.BocBai
            };
            buffer = msg.ToByteArray();
            _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, OnMessageSent, null);
        }

        private void btnSS_Click(object sender, EventArgs e)
        {
            var msg = new ChatMessage()
            {
                SenderName = _userName,
                MsgBody = "",
                CmdType = CommandType.SanSang
            };
            buffer = msg.ToByteArray();
            _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, OnMessageSent, null);
            groupBox7.Controls.Cast<Control>().Where(x => x is Label).ToList()[0].Text = "Sẵn Sàng";
        }

        private void btnboqua_Click(object sender, EventArgs e)
        {
            
            stop = false;
            groupBox7.Controls.Cast<Control>().Where(x => x is Label).ToList()[0].Text = "Qua Lượt";
            var msg = new ChatMessage()
            {
                CmdType = CommandType.Boqua,
                SenderName = _userName,
                MsgBody =""
            };
            buffer = msg.ToByteArray();
            _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, OnMessageSent, null);
            toiluot(false);
        }
        void SendMessage(ChatMessage _msg)
        {
            buffer = _msg.ToByteArray();
            _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, OnMessageSent, null);
        }

        private void btnMoBai_Click(object sender, EventArgs e)
        {
            var gr = (sender as Button).Parent;
            var msg = new ChatMessage()
            {
                CmdType = CommandType.MoBai,
                SenderName = gr.Text,
                MsgBody = "mo bai"
            };
            SendMessage(msg);

        }

        
    }
}
